package com.yang.String_;

public class LeetCode05 {
    public static void main(String[] args) {
        SolutionLeetCode05 solutionLeetCode05 = new SolutionLeetCode05();
        String s = ".. . ..";
        System.out.println(solutionLeetCode05.replaceSpace(s.toString()));
    }
}


class SolutionLeetCode05 {
    public String replaceSpace(String s) {
        if(s == null || s.length() == 0)return null;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == ' '){
                stringBuilder.append(' ');
                stringBuilder.append(' ');
            }
        }
        // 这里是一个关键让left等于扩容前的长度 right=扩容后的长度，这样right必然在left的前面
        int left = s.length() - 1;
        s += stringBuilder.toString();
        int right = s.length() - 1;
        char[] c = s.toCharArray();


        while (left >= 0){
            if(c[left] == ' '){
                c[right--] = '0';
                c[right--] = '2';
                c[right] = '%';
            }
            else {
                c[right] = c[left];
            }
            left--;
            right--;
        }
        return new String(c);
       /*========方法1直接新建StringBuilder然后对字符串进行判断，如果为空格直接替换=====
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == ' '){
                stringBuilder.append("%20");
            }else {
                stringBuilder.append(s.charAt(i));
            }
        }
        return stringBuilder.toString();*/
    }
}
